package com.hongyu.manager.media.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.hongyu.manager.media.manager.dao.TxtMapper;
import com.hongyu.manager.media.manager.model.bean.Txt;
import com.hongyu.manager.media.manager.service.TxtService;
import com.hongyu.manager.media.manager.utils.task.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.List;

@Service
public class TxtServiceImpl implements TxtService {
    private static final Logger LOG = LoggerFactory.getLogger(TxtServiceImpl.class);
    @Autowired
    TxtMapper txtMapper;
    @Override
    public void saveTxtFileinfor(File f) {
        String path = f.getAbsolutePath();
        File file;
        Txt txt = new Txt();
        if (path.endsWith(".txt")){
            LOG.info(path);
            txt.setName(f.getName().replace(".txt","").replace(" ",""));
            file=new File(f.getParent());
            txt.setTitle(file.getName());
            file=new File(file.getParent());
            txt.setWebSite(file.getName());
            txt.setPath(path);
            Txt tx = txtMapper.findTxtByName(txt.getName());
            if (tx == null) {
                txtMapper.saveTxtFileinfor(txt);
            } else {
                LOG.info(txt.getName() + "文件已存在");
            }

        }






//
//            Txt tx = txtMapper.findTxtByName(strs[2]);
//            if (tx == null) {
//                txtMapper.saveTxtFileinfor(txt);
//            } else {
//                LOG.info(strs[2] + "文件已存在");
//            }



    }

    @Override
    public List<Txt> getList(Txt txt) {
        List<Txt> txts=txtMapper.getList(txt);
        return txts;
    }

    @Override
    public Txt findTxt(Integer id) {
       Txt txt= txtMapper.findTxtById(id);

       BufferedReader br = null;
       String content="";
        try
        {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(txt.getPath()))));//UTF-8
        String str = null;
        int i = 0;
        while ((str = br.readLine()) != null)
        {
            if (StrUtil.isNotBlank(str))
            {
                content=content+str;
            }
            i++;
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            br.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

        txt.setContent(content);

        return txt;
    }
}
